// content-scripts/services/clipboard-service.js
let permissionStatus = null;
const errorMessages = {
    PERMISSION_DENIED: '剪贴板权限被拒绝',
    BLOB_CONVERSION_FAILED: '图片转换失败',
    PERMISSION_CHECK_FAILED: '权限检查失败'
};

// 权限状态缓存
const checkPermission = async () => {
    if (!permissionStatus) {
        try {
            permissionStatus = await navigator.permissions.query({
                name: 'clipboard-write'
            });
        } catch (error) {
            handleError(error, 'PERMISSION_CHECK_FAILED');
        }
    }

    if (permissionStatus.state === 'denied') {
        handleError(new Error('PERMISSION_DENIED'));
    }
    return true;
};

// 错误处理函数
const handleError = (error, code) => {
    const message = errorMessages[code] || error.message;
    const wrappedError = new Error(message, { cause: error });
    console.error(`[ClipboardService] ${message}`, error);
    throw wrappedError;
};

// 通用 Canvas 转换
const getBlobFromCanvas = (canvas) => {
    return new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
            blob ? resolve(blob) : reject(new Error('BLOB_CONVERSION_FAILED'));
        }, 'image/png', 0.9);
    });
};

// 导出接口
export const ClipboardService = {
    copyImage: async (canvas) => {
        await checkPermission();
        try {
            const blob = await getBlobFromCanvas(canvas);
            await navigator.clipboard.write([
                new ClipboardItem({ 'image/png': blob })
            ]);
            return true;
        } catch (error) {
            handleError(error);
        }
    },

    copyText: async (text) => {
        await checkPermission();
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (error) {
            handleError(error);
        }
    },

    copy: async (text, canvas) => {
        await checkPermission();
        try {
            const [blob] = await Promise.all([
                getBlobFromCanvas(canvas),
                navigator.clipboard.writeText(text)
            ]);

            await navigator.clipboard.write([
                new ClipboardItem({
                    'text/plain': new Blob([text], { type: 'text/plain' }),
                    'image/png': blob
                })
            ]);
            return true;
        } catch (error) {
            handleError(error);
        }
    }
};
